package finanz.kontrolle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import classes.Funcoes;
import classes.Parametros;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class FinanzKontrolleDroidActivity extends Activity implements OnClickListener {
	private boolean logado = false;
	private Parametros par = Parametros.getInstance();

	public void onCreate( Bundle savedInstanceState ) {
		super.onCreate( savedInstanceState );
		setContentView( R.layout.main );

		if ( par.getUrl().toString().equals( "" ) )
			par.setUrl( getResources().getString( R.string.urlSite ) );
		else {
			TextView tvUrl = ( TextView ) findViewById( R.id.tvUrl );
			tvUrl.setText( par.getUrl().toString() );
		}
		
		Button btnLogin = ( Button ) findViewById( R.id.btnLogin );
		btnLogin.setOnClickListener( this );
	}

	public void onClick( View arg0 ) {
		switch ( arg0.getId()  ) {
			case R.id.btnLogin:
				
					int mensagem = R.string.msgSucessoLogin;
					String msg = "";

					EditText txtLogin = ( EditText ) findViewById( R.id.txtLogin );
					EditText txtSenha = ( EditText ) findViewById( R.id.txtSenha );
					
					if ( txtLogin.getText().length() <= 0 )
						 mensagem =  R.string.msgPreenchaLogin;
					else if ( txtSenha.getText().length() <= 0 )
						 mensagem =  R.string.msgPreenchaSenha;
					else {
						mensagem = this.logar( txtLogin.getText().toString(), txtSenha.getText().toString() );
						if ( mensagem == R.string.msgSucessoLogin )
							msg = getResources().getString( R.string.msgSucessoLogin ) + " " + par.getNome() + "!";
					}
					
					Toast t;
					if ( msg != "" ) {
						t = Toast.makeText( this, msg, Toast.LENGTH_SHORT );
					}
					else {
						t = Toast.makeText( this, mensagem, Toast.LENGTH_SHORT );
					}
						t.setGravity( Gravity.CENTER, 0, 0 );
						t.show();
						
					if ( this.logado ) {
						Intent i = new Intent( FinanzKontrolleDroidActivity.this, HomeActivity.class );
						startActivity( i );
						finish();
					}
				break;
		}
	}

	protected int logar( String mLogin, String mPassword ) {
		int mensagem = 0;
		
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlLogin );
		
		HttpParams httpParameters = new BasicHttpParams();
		int timeoutConnection = 3000;
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		int timeoutSocket = 5000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		
		HttpClient httpclient = new DefaultHttpClient( httpParameters );
	    HttpPost httppost = new HttpPost( strUrl  );

	    try {
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("Login", mLogin));
	        nameValuePairs.add(new BasicNameValuePair("Senha", mPassword));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        HttpResponse response = httpclient.execute(httppost);

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );

	        try {
				JSONObject jo = new JSONObject( retorno.toString() );
				
				if ( jo.getBoolean( "logged_in" ) ) {
					mensagem = R.string.msgSucessoLogin;
					this.logado = true;
					
					par.setNome( jo.getString( "email" ) );
					par.setDatabase( jo.getString( "banco" ) );
					par.setPessoaID( jo.getString( "pessoaID" ) );
					
				} else if ( !jo.getBoolean( "logged_in" ) )
					mensagem = R.string.msgEmailSenhaInvalido ;
				else
					mensagem = R.string.msgErroConectar ;
				 
			} catch (JSONException e) {
				mensagem = R.string.msgErroConectar;
			}
	    } catch (ClientProtocolException e) {
	    	mensagem = R.string.msgErroConectar;
	    } catch (IOException e) {
	    	mensagem = R.string.msgErroConectar;
	    }

	    return mensagem;
	}
	
	public boolean onCreateOptionsMenu( Menu menu ) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate( R.menu.menuhome, menu );
		
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch( item.getItemId() ) {
			case R.id.opcc1:
				Intent i = new Intent( FinanzKontrolleDroidActivity.this, TrocaUrlActivity.class );
				startActivity( i );
			break;
			case R.id.opcc2:
				Toast t = Toast.makeText( this, "Tenha um bom dia!", Toast.LENGTH_SHORT );
				t.setGravity( Gravity.CENTER, 0, 0 );
				t.show();
				
				finish();
	            System.exit(0);
			break;
		}
		
		return true;
	}
	
}